/* eslint-disable react/no-array-index-key */
import React, {useState, useEffect, useRef, useMemo} from 'react';
import {QuestionCircleOutlined, SettingOutlined} from '@ant-design/icons';
import {Button, Tooltip, Empty, Drawer, Checkbox, Row, Col} from 'antd';

import DataEchart from '~/component/DataEchart';
import {buildTipText as buildTip} from '~/component/SearchForm/helps';
import {groupByData} from '~/utils/common/reportIndicator';
import {lineOptions} from '~/utils/common/reportEcharts';

function LineChart(props) {
    const {reportMeasure, dataSource, dateDim, period} = props;
    const [measureId, setMeasureId] = useState();
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [checkedGroup, setCheckedGroup] = useState([]);
    const [legendOptions, setLegendOptions] = useState([]);
    // 分组数据
    const [groupData, setGroupData] = useState();

    const echartEl = useRef();

    // echart options
    const [options, setOptions] = useState({});

    // 报表echart提示文字
    const tipText = useMemo(() => buildTip(reportMeasure), [reportMeasure]);

    useEffect(() => {
        if (echartEl.current) {
            // off 避免重复绑定
            echartEl.current.off('legendselectchanged');
            echartEl.current.on('legendselectchanged', params => {
                const res = [];
                const keys = Object.keys(params.selected);
                const values = Object.values(params.selected);
                for (let i = 0; i < values.length; i++) {
                    if (values[i]) {
                        res.push(keys[i]);
                    }
                }
                setCheckedGroup(res);
            });
        }
    });

    useEffect(() => {
        // setup default
        if (reportMeasure.length) {
            setMeasureId(reportMeasure[0].measureId);
        }
    }, [reportMeasure]);

    useEffect(() => {
        getDataMap(dataSource, measureId);
    }, [measureId, dataSource]);

    useEffect(() => {
        if (groupData) {
            const newOptions = lineOptions(groupData, period, buildSelected());
            setOptions(newOptions);
        }
    }, [groupData, legendOptions, checkedGroup, period]);

    // 指标切换
    function onReportChane(measureId) {
        setMeasureId(measureId);
    }

    /**
     * 获取echart数据, 筛选分类,生成echart数据
     * @param {object} dataSource 原始数据
     * @param {string} measureId 筛选数据
     */
    function getDataMap(dataSource, measureId) {
        if (!measureId) {
            return;
        }
        const item = reportMeasure.filter(item => item.measureId === measureId);
        if (item.length) {
            const groupData = groupByData(dataSource, dateDim, `field${item[0].sn}`);
            groupData.sort((a, b) => parseFloat(b.point[0].value) - parseFloat(a.point[0].value));
            setGroupData(groupData);

            const allList = groupData.map(e => e.name).filter(item => item !== '');
            setLegendOptions(allList);
            // 截取默认选择图例
            const checked = allList.slice(0, 5);
            setCheckedGroup(checked);
        }
    }
    // build echarts selected part
    function buildSelected(allList = legendOptions, checked = checkedGroup) {
        const res = {};
        for (const e of allList) {
            if (checked.includes(e)) {
                res[e] = true;
            }
            else {
                res[e] = false;
            }
        }
        return res;
    }

    // 抽屉
    function handleDrawer() {
        setDrawerVisible(!drawerVisible);
    }

    function handleCheckedGroup(value) {
        setCheckedGroup(value);
    }

    return (
        <div className="echartContent">
            <div className="chartHeader">
                <h4>指标</h4>
                <Tooltip placement="topLeft" overlayClassName="measure-tooltip" title={tipText}>
                    <QuestionCircleOutlined class="desIcon" />
                </Tooltip>
                <div className="moreSpan">
                    {reportMeasure.map(item => (
                        <Tooltip placement="top" title={item.reportName} key={item.measureId} >
                            <Button
                                size="default"
                                type="link"
                                style={
                                    {
                                        color: item.measureId === measureId
                                            ? '#528ff2'
                                            : '#ccc'
                                    }
                                }
                                onClick={() => {
                                    onReportChane(item.measureId);
                                }} class="reportNameText"
                            >
                                {item.reportName}
                            </Button>
                        </Tooltip>
                    ))}
                </div>
                <Button className="setting" type="default" onClick={handleDrawer}>
                    <SettingOutlined />
                    显示设置
                </Button>
            </div>
            {
                dataSource.length
                    ? <DataEchart data={options} echartEl={echartEl} />
                    : <Empty imageStyle={{height: 70}} image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }

            <Drawer
                title="选择折线"
                placement="right"
                closable
                onClose={handleDrawer}
                visible={drawerVisible}
                className="echartDrawer"
                width={340}
            >
                <Checkbox.Group style={{width: '100%'}} value={checkedGroup} onChange={handleCheckedGroup}>
                    <Row>
                        {
                            legendOptions.map((entry, index) => (
                                <Col key={index} span={24}>
                                    <Tooltip title={entry} placement="left">
                                        <Checkbox value={entry} className="item">
                                            {entry}
                                        </Checkbox>
                                    </Tooltip>
                                </Col>
                            ))
                        }
                    </Row>
                </Checkbox.Group>
            </Drawer>
        </div>
    );
}

export default LineChart;
